package com.blb.demo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁对象等待
 * Lock对象
 */
public class WaitThread2 {

    public Object obj = new Object();

    private  Lock lock = new ReentrantLock();

    private  Condition condition = lock.newCondition();

    public void testWait() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "执行testWait 等待");
            condition.await();
            System.out.println(Thread.currentThread().getName() + "结束testWait");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void testNotify() {
        lock.lock();
        try {
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        WaitThread2 waitThread = new WaitThread2();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                waitThread.testWait();
            }).start();
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        waitThread.testNotify();
    }
}
